package com.lw.extraceim.ui.activity.es;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.lw.extraceim.R;
import com.lw.extraceim.app.AppConstants;
import com.lw.extraceim.loader.ExpressSheetLoader;
import com.lw.extraceim.model.CustomerInfo;
import com.lw.extraceim.model.ExpressSheet;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.MainActivity;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.ui.activity.customer.CustomerEditActivity;
import com.lw.extraceim.ui.activity.customer.CustomerListActivity;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.util.TextUtil;
import com.lw.extraceim.view.ExtraceToolbar;

import org.json.JSONException;

import java.util.Objects;

import okhttp3.Call;

/**
 * @Author : qutangjun
 * @Change : liwei
 * @Email : 1759840027@qq.com
 * @Description :快件信息编辑界面
 * @Date : 2019/4/14 11:09
 */
public class WriteExpressSheetActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "WriteExpressSheetActivi";

    private ExtraceToolbar mToolbar;

    private String action;
    private ExpressSheet expressSheet;

    private EditText mEtExpressNumber;
    //寄件人信息
    private LinearLayout mSenderLayout;
    private TextView mTvSenderName;
    private TextView mTvSenderPhone;
    private TextView mTvSenderAddress;
    //收件人信息
    private LinearLayout mReciverLayout;
    private TextView mTvReciverName;
    private TextView mTvReciverPhone;
    private TextView mTvReciverAddress;

    private ImageView mIvSenderList;
    private ImageView mIvReciverList;

    //上传图片
    private ImageButton mIbUpdateImg;
    private ImageView mImageExpressSheet;

    private Button mButtonSave;

    private CustomerInfo sender; //寄件人信息
    private CustomerInfo reciver; //收件人信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_write_express_sheet);
        mToolbar = findViewById(R.id.toolbar);
        initToolBar();
//            mCityPickerView = new CityPickerView();
//            mCityPickerView.init(this);//初始化cityPickerView

        mEtExpressNumber = findViewById(R.id.et_express_number);

        //寄件人信息
        mSenderLayout = findViewById(R.id.ll_sender_info);
        mTvSenderName = findViewById(R.id.tv_sender_name);
        mTvSenderPhone = findViewById(R.id.tv_sender_phone);
        mTvSenderAddress = findViewById(R.id.tv_sender_address);

        //收件人信息
        mReciverLayout = findViewById(R.id.ll_reciver_info);
        mTvReciverName = findViewById(R.id.tv_reciver_name);
        mTvReciverPhone = findViewById(R.id.tv_reciver_phone);
        mTvReciverAddress = findViewById(R.id.tv_reciver_address);

        mIvSenderList = findViewById(R.id.iv_sender_list);
        mIvReciverList = findViewById(R.id.iv_reciver_list);

        mIbUpdateImg = findViewById(R.id.ib_update_img);
        mImageExpressSheet = findViewById(R.id.image_express_sheet);

        mButtonSave = findViewById(R.id.btn_save);

    }

    /**
     * 初始化toolBar
     */
    protected void initToolBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setBackButtonOnClickListerner(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WriteExpressSheetActivity.this.finish();
            }
        });
        refreshTitle();
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        action = intent.getStringExtra("action");
        expressSheet = (ExpressSheet) intent.getSerializableExtra("expressSheet");
        sender = expressSheet.getSender();
        reciver = expressSheet.getRecever();
    }

    @Override
    public void refreshUI() {
        if (expressSheet != null) {
            mEtExpressNumber.setText(expressSheet.getId());
            sender = expressSheet.getSender();
            reciver = expressSheet.getRecever();
        }

        refreshSender();
        refreshReciver();
        refreshTitle();
    }

    @Override
    public void initEvent() {

        mSenderLayout.setOnClickListener(this);
        mReciverLayout.setOnClickListener(this);
        mIbUpdateImg.setOnClickListener(this);
        mIvSenderList.setOnClickListener(this);
        mIvReciverList.setOnClickListener(this);
        mButtonSave.setOnClickListener(this);
    }


    private EditText currentEdit;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_sender_info: {
                CustomerEditActivity.actionStartForResult(this, CustomerEditActivity.EDIT_SENDER, sender);
                break;
            }
            case R.id.ll_reciver_info: {
                CustomerEditActivity.actionStartForResult(this, CustomerEditActivity.EDIT_RECIVER, reciver);
                break;
            }
            case R.id.btn_back: {
                this.finish();
                break;
            }
            case R.id.ib_update_img: {
                showDialog();
                break;
            }
            case R.id.iv_reciver_list: {
                CustomerListActivity.actionStartForResult(this, CustomerEditActivity.CUSTOMER_EDIT_RECIVERE_RESULT_CODE);
                break;
            }
            case R.id.iv_sender_list: {
                CustomerListActivity.actionStartForResult(this, CustomerEditActivity.CUSTOMER_EDIT_SENDER_RESULT_CODE);
                break;
            }
            case R.id.btn_save: {
                save();
            }
        }
    }


    //拍照回传码
    private static final int CAMERA_REQUEST_CODE = 103;
    // 相册选择回传码
    public final static int GALLERY_REQUEST_CODE = 104;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case CustomerEditActivity.CUSTOMER_EDIT_ACTIVITY_CODE: {
                if (resultCode == CustomerEditActivity.CUSTOMER_EDIT_SENDER_RESULT_CODE) {
                    sender = (CustomerInfo) data.getSerializableExtra("customerInfo");
                    if (sender == null) {
                        Toast.makeText(this, "寄件人信息编辑错误！", Toast.LENGTH_SHORT).show();
                    }
                    refreshSender();
                } else if (resultCode == CustomerEditActivity.CUSTOMER_EDIT_RECIVERE_RESULT_CODE) {
                    reciver = (CustomerInfo) data.getSerializableExtra("customerInfo");
                    if (reciver == null) {
                        Toast.makeText(this, "收件人信息编辑错误！", Toast.LENGTH_SHORT).show();
                    }
                    refreshReciver();
                }
                break;
            }
            case GALLERY_REQUEST_CODE: {
                // 获取图片
                try {
                    //该uri是上一个Activity返回的
                    Uri imageUri = data.getData();
                    if (imageUri != null) {
                        Bitmap bit = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        Log.i("bit", String.valueOf(bit));
                        mImageExpressSheet.setImageBitmap(bit);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case CAMERA_REQUEST_CODE: {
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    mImageExpressSheet.setImageBitmap(bitmap);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 刷新寄件人信息
     */
    private void refreshSender() {
        if (sender != null) {
            mTvSenderName.setText(sender.getName());
            mTvSenderPhone.setText(sender.getTelCode());
            mTvSenderAddress.setText(sender.getRegionString() + " " + sender.getAddress());
        }
    }

    /**
     * 刷新收件人信息
     */
    private void refreshReciver() {
        if (reciver != null) {
            mTvReciverName.setText(reciver.getName());
            mTvReciverPhone.setText(reciver.getTelCode());
            mTvReciverAddress.setText(reciver.getRegionString() + " " + reciver.getAddress());
        }
    }

    /**
     * 刷新标题
     */
    private void refreshTitle() {
        if (action != null) {
            if (Objects.equals(action, AppConstants.ACTION_NEW)) {
                mToolbar.setTitleText("快递单填写");
            } else if (Objects.equals(action, AppConstants.ACTION_EDIT)) {
                mToolbar.setTitleText("修改快递单信息");
            }
        }
    }

    private HttpResponseParamCallback callback = new HttpResponseParamCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            alert("网络错误" + e.getMessage());
            Log.d(TAG, "onError: 网络错误" + e.getMessage());
        }

        @Override
        public void onResponse(HttpResponseParam response, int id) {
            Log.d(TAG, "onResponse: " + response.reseponseJson.toString());
            if (response.code.getCode() == ResponseCode.SUCESS) {
                try {
                    expressSheet = JsonUtils.fromJson(response.reseponseJson.getJSONObject("es").toString(), new TypeToken<ExpressSheet>() {
                    });
                    expressSheet.onLoad();
                    alert("保存成功");
                } catch (JSONException e) {
                    e.printStackTrace();
                    alert("解析错误");
                    Log.d(TAG, "onResponse: " + e.getMessage());
                }
            } else {
                alert("保存失败," + response.code.getMessage());
            }
        }
    };

    /**
     * 保存快件信息
     */
    public void save() {
        if (checkInput()) {
            ExpressSheetLoader esLoader = new ExpressSheetLoader(this);
            Log.d(TAG, "save: " + application.getUserInfo());
            if (!expressSheet.isSaved()) {
                esLoader.save(expressSheet, application.getUserInfo().getuId(), callback);
            } else {
                esLoader.update(expressSheet, callback);
            }
        }
    }

    /**
     * 检查输入是否完整
     *
     * @return
     */
    public boolean checkInput() {
        expressSheet = (expressSheet == null ? new ExpressSheet() : expressSheet);
        String esId = mEtExpressNumber.getText().toString();
        if (!TextUtil.isNull(esId)) {
            expressSheet.setId(esId);
        } else {
            alert("快件编号不能为空");
            return false;
        }

        if (sender != null && sender.getId() != 0) {
            expressSheet.setSender(sender);
        } else {
            alert("请填写寄件人信息");
            return false;
        }

        if (reciver != null && reciver.getId() != 0) {
            expressSheet.setRecever(reciver);
        } else {
            alert("请填写收件人信息");
            return false;
        }

        //检查快件图片

        return true;

    }

    public void loadEs() {

    }


    /**
     * 弹出框
     */
    private void showDialog() {
        final AlertDialog build = new AlertDialog.Builder(this).create();
        //自定义布局
        View view = getLayoutInflater().inflate(R.layout.update_select_dialog, null);
        //把自定义的布局设置到dialog中，注意，布局设置一定要在show之前。从第二个参数分别填充内容与边框之间左、上、右、下、的像素
        build.setView(view, 0, 0, 0, 0);
        //一定要先show出来再设置dialog的参数，不然就不会改变dialog的大小了
        build.show();
        //得到当前显示设备的宽度，单位是像素
        int width = getWindowManager().getDefaultDisplay().getWidth();
        //得到这个dialog界面的参数对象
        WindowManager.LayoutParams params = build.getWindow().getAttributes();
        //设置dialog的界面宽度
        params.width = width - (width / 6);
        //设置dialog高度为包裹内容
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的重心
        params.gravity = Gravity.CENTER;
        //dialog.getWindow().setLayout(width-(width/6), LayoutParams.WRAP_CONTENT);
        //用这个方法设置dialog大小也可以，但是这个方法不能设置重心之类的参数，推荐用Attributes设置
        //最后把这个参数对象设置进去，即与dialog绑定
        build.getWindow().setAttributes(params);
        Button leftButton = (Button) view.findViewById(R.id.update_dialog_left);
        Button rightButton = (Button) view.findViewById(R.id.update_dialog_right);
        leftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImagFromAlbum();
                build.dismiss();
            }
        });
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
                build.dismiss();
            }
        });
    }

    /**
     * 从相册选取图片
     */
    public void selectImagFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, GALLERY_REQUEST_CODE);
    }

    /**
     * 照相
     */
    public void takePhoto() {
        // 跳转到系统的拍照界面
        Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intentToTakePhoto, CAMERA_REQUEST_CODE);//启动相机
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePhoto();
            } else {
                // Permission Denied
                Toast.makeText(WriteExpressSheetActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }

        if (requestCode == GALLERY_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                selectImagFromAlbum();
            } else {
                // Permission Denied
                Toast.makeText(WriteExpressSheetActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public void onBackPressed() {
        super.finish();
    }

    /**
     * 启动activity
     *
     * @param context
     * @param action
     * @param expressSheet
     */
    public static void actionStart(Activity context, String action, ExpressSheet expressSheet) {
        Intent intent = new Intent(context, WriteExpressSheetActivity.class);
        intent.putExtra("action", action);
        intent.putExtra("expressSheet", expressSheet);
        context.startActivity(intent);
    }
}
